package com.yanghui.lingyue.functions.apiBase

import com.alibaba.fastjson.JSONObject
import com.icedata.sika.bridge.*
import com.icedata.sika.core.CommandProcessor
import com.icedata.sika.core.Sika
import com.icedata.sika.util.Logger
import com.yanghui.lingyue.data.Command
import com.yanghui.lingyue.functions.AbstractFunction
import com.yanghui.lingyue.utils.functionUtils.FunctionUtils
import com.yanghui.lingyue.utils.netUtils.HttpJsonUtils
import java.net.URLEncoder
import java.util.*

object SendAIReply: AbstractFunction() {
    override val name: String = "AIReply"

    override suspend fun parse(event: SikaEvent, sika: Sika): LinkedList<Command> {
        val command = LinkedList<Command>()
        if (event is SikaUserEvent) return command
        event as SikaGroupEvent
        if (!FunctionUtils.atBot(event)) return command
        if (!FunctionUtils.checkValid(event)) return command
        if (event.sendGroup.id !in enableGroup) return command

        val param = FunctionUtils.extractKeyword(event, "AI")
        param?.let {
            command.add(Command(event, name, it))
        }
        return command
    }

    override suspend fun execute(command: Command, sika: Sika): CommandProcessor.Result {
        if (command.param.isNotBlank()) {
            /* 解析JSON数据 **/
            val response: JSONObject = HttpJsonUtils.getJsonObjectFromURLMethodGet(getRequestURL(command.param))
            try {
                Objects.requireNonNull(response)
            } catch (e: NullPointerException) {
                Logger.logError(e)
            }
            var content = response.getString("content")
            /* 封装JSON数据 **/
            content = decodeAnswer(content!!)
            val builder = SikaMessageChainBuilder()
            builder.add(SikaAtMessage(command.sender))
            builder.add(SikaPlainMessage(" $content"))
            command.sendGroup?.sendMessage(builder)
        }
        return CommandProcessor.Result.ADOPT
    }

    private fun decodeAnswer(answer: String): String {
        return answer.replace("{br}", "\n")
    }

    private fun getRequestURL(question: String): String {
        return "https://api.qingyunke.com/api.php?key=free&appid=0&msg=" + URLEncoder.encode(question)
    }
}